package com.leoman.spinningmachine.tab1;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.leoman.spinningmachine.R;
import com.leoman.spinningmachine.base.BaseFragment;
import com.leoman.spinningmachine.constant.Constant;
import com.leoman.spinningmachine.http.APIResponse;
import com.leoman.spinningmachine.http.WebServiceApi;
import com.leoman.spinningmachine.ocr.CameraManager;
import com.leoman.spinningmachine.ocr.InactivityTimer;
import com.leoman.spinningmachine.ocr.SweepActivityHandler;
import com.leoman.spinningmachine.ocr.ViewfinderView;
import com.leoman.spinningmachine.util.SharedPreferencesUtils;

import java.io.IOException;
import java.util.Vector;

import butterknife.BindView;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * 扫码
 */
public class SweepFragment extends BaseFragment implements SurfaceHolder.Callback {

    @BindView(R.id.viewfinder_view)
    ViewfinderView viewfinderView;

    private SweepActivityHandler handler;
    private boolean hasSurface;// surface有没有被绘制
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private boolean vibrate;// 完成扫描时是否震动提示
    private String userId;
    private String token;


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden)
            pause();
        else
            resume();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fg_sweep;
    }

    @Override
    protected void initView(View view) {
        token = SharedPreferencesUtils.getInstance().getString("token");
        userId = SharedPreferencesUtils.getInstance().getString(Constant.USERID);
        CameraManager.init(getActivity().getApplication());

        hasSurface = false;
        inactivityTimer = new InactivityTimer(getActivity());// activity静止一段时间会自动关闭
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        resume();
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    private void pause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    private void resume() {
        SurfaceView surfaceView = (SurfaceView) getView().findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        vibrate = true;
    }


    @Override
    public void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    // 初始化照相机
    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new SweepActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private static final long VIBRATE_DURATION = 200L;

    // 启动声音功能
    private void playBeepSoundAndVibrate() {
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }


    // 二维码扫描结果数据

    public void handleDecode(Result obj, Bitmap barcode) {
        inactivityTimer.onActivity();
//         viewfinderView.drawResultBitmap(barcode);//画结果图片
        playBeepSoundAndVibrate();// 启动声音效果

        String result = obj.getText();
        Log.e("扫描结果：", result);
        Toast.makeText(getActivity(), "扫描结果：" + result, Toast.LENGTH_LONG).show();
        if(!TextUtils.isEmpty(result)){
            WebServiceApi.getInstance().qrCodeOpenDoor(token,"",this,1);
        }
        pause();
    }

    @Override
    public void OnSuccessData(APIResponse apiResponse, Integer tag) {
        super.OnSuccessData(apiResponse, tag);

    }

    @Override
    public void OnFailureData(String error, Integer tag) {
        super.OnFailureData(error, tag);
    }

    @Override
    public void OnErrorData(String code, Integer tag) {
        super.OnErrorData(code, tag);
    }
}
